<?php

namespace App\Models;

use App\Api\ImageHelper;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\QueryException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * App\Models\GoodOrder
 *
 * @property int $id
 * @property int $user_id 用户id
 * @property string $order_no 订单编号
 * @property int $pay_way 支付方式:0=余额支付,1=微信支付
 * @property string $amount 支付金额
 * @property int $method 收货方式:0=快递配送,1=到店自提
 * @property mixed|null $address 收货地址信息
 * @property int $deliver 发货方式:0=待安排,1=平台发货,2=门店发货
 * @property string $shop_id 发货门店ID
 * @property string|null $courier_com 快递公司
 * @property string|null $courier_number 快递单号
 * @property string|null $courier_fee 快递运费
 * @property string $order_time 下单时间
 * @property string|null $pay_time 付款时间
 * @property string|null $send_time 发货时间
 * @property string|null $finish_time 完成时间
 * @property int|null $province_id 省ID
 * @property int $city_id 市ID
 * @property int $district_id 区ID
 * @property int $state 订单状态:0=待支付,1=待发货,2=待收货,3=已完成,4=已评价,5=已退款
 * @property int $is_apply 是否申请退款:0=否,1=是
 * @property string|null $refund_time 退款时间
 * @property string|null $refund_no 退款单号
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\GoodOrderDetail[] $details
 * @property-read int|null $details_count
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder query()
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereCityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereCourierNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereDeliver($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereDistrictId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereFinishTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereIsApply($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereMethod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereOrderNo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereOrderTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder wherePayTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder wherePayWay($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereProvinceId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereRefundNo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereRefundTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereSendTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereShopId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereState($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property-read string $state_text
 * @property-read \App\Models\ShopUser|null $shop
 * @property-read \App\Models\User|null $user
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereCourierCom($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereCourierFee($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodOrder whereUserId($value)
 */
class GoodOrder extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'good_orders';

    protected $casts = [ 'address'=>'json' ];

    protected $appends = [
        'state_text'
    ];

    protected $hidden = [];

    protected static function booted()
    {
        self::updating(function (GoodOrder $order){
            if ($order->isDirty("state")){
//                if ($order->state==2){
//                    OrderCommission::addGoodCommission($order);
//                }
                if ($order->state==3&&$order->is_apply==0){
                    OrderCommission::updateCommissionOrders($order->order_no,"商品订单分成");
                }
            }
        });
        self::deleting(function (GoodOrder $order){
            GoodOrderDetail::query()->where("oid",$order->order_no)->delete();
            OrderCommission::whereOrderId($order->order_no)->delete();
        });
    }



    public static function getStateList(): array
    {
        return ['待支付','待发货','待收货','已完成','已评价','已退款'];
    }

    public function getStateTextAttribute(): string
    {
        return self::getStateList()[$this->attributes['state']];
    }

    public function shop(): HasOne
    {
        return $this->hasOne(ShopUser::class,"id","shop_id");
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class,"id","user_id")->select(['id','nickname','avatar']);
    }

    public function details(): HasMany
    {
        return $this->hasMany(GoodOrderDetail::class,"oid","order_no");
    }

    /**
     * 订单列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id): array
    {
        $state = request()->input("state",0);
        $limit = request()->input("limit",10);
        $list = self::query()->with(['details'=>function($query){
            $query->withExists('apprise');
        }])->when($state>-1,function ($query) use ($state) {
            $query->where("state",$state);
        })->where("user_id",$user_id)->orderByDesc("id")
            ->paginate($limit);
        foreach ($list as $item){
            $item->details = ImageHelper::handleDetails($item);
        }
        $items = $list->items();
        $total = $list->total();
        $lastPage = $list->lastPage();
        return [
            'items'=>$items,
            'total'=>$total,
            'lastPage'=>$lastPage
        ];
    }

    /**
     * 订单详情
     * @param $order_no
     * @return array
     */
    public static function getDetail($order_no): array
    {
        $order = self::query()->where("order_no",$order_no)
            ->with(['details'=>function($query){
                $query->withExists('apprise');
            }])
            ->first();
        if ($order){
            $order->code = "";
            if ($order->method){
                if ($order->state==2){
                    $order->code = url('api/v1/code',['order_no'=>$order_no]);
                }
            }
            ImageHelper::handleDetails($order);
            if ($order->state==2){
                $confirmDay = \App\Api\Models\Config::getName("confirm_hours");
                $confirmSeconds = intval($confirmDay)*3600*24;
                $diffSeconds = now()->diffInSeconds($order->pay_time);
                $seconds = $confirmSeconds-$diffSeconds;
                $order->d_time = now()->addSeconds($seconds)->diffForHumans(['parts' => 2]);
            }
            $companys = collect(config('platform.company'))->pluck("title","value")->toArray();
            if($order->courier_com){
                $order->courier_com_name = $companys[$order->courier_com];
            }else{
                $order->courier_com_name = "";
            }
        }
        return ['detail'=>$order];
    }


}
